package com.fjut.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.fjut.exception.CustomException;
import com.fjut.model.vod.Video;
import com.fjut.service.VideoService;
import com.fjut.service.VodService;
import com.fjut.utils.ConstantPropertiesUtil;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class VodServiceImpl implements VodService {

    private static final String PROCEDURE_NAME = "LongVideoPreset";
    private static final String AREA_REGION = "ap-guangzhou";
    private static final String MEDIA_FILE_PATH = "C:\\Users\\HASEE\\OneDrive\\桌面\\毕设\\毕设项目\\课程视频\\";
    private static final String VIDEO_SOURCE_ID = "videoSourceId";
    private static final String APP_ID = "appId";
    private static final String END_POINT = "vod.tencentcloudapi.com";

    @Autowired
    private VideoService videoService;

    @Value("${tencent.video.appId}")
    private String appId;

    @Value("${tencent.video.playKey}")
    private String playKey;

    @Override
    public String upload(MultipartFile file) {
        VodUploadClient client = new VodUploadClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(MEDIA_FILE_PATH + file.getOriginalFilename());
        request.setProcedure(PROCEDURE_NAME);
        try {
            VodUploadResponse response = client.upload(AREA_REGION, request);
            return response.getFileId();
        } catch (Exception e) {
            // 业务方进行异常处理
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean deleteVideoById(String fileId) {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(END_POINT);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(fileId);
            // 返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            System.out.println(DeleteMediaResponse.toJsonString(resp));
            return true;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Map<String, Object> getPlayAuth(Long courseId, Long videoId) {
        Video video = videoService.getById(videoId);
        if (video == null) {
            return null;
        }
        String psign;
        Map<String, Object> contentInfo = new HashMap<>();
        contentInfo.put("audioVideoType","RawAdaptive");
        contentInfo.put("rawAdaptiveDefinition",10);
        contentInfo.put("imageSpriteDefinition",10);
        Map<String, Object> urlAccessInfo = new HashMap<>();
        urlAccessInfo.put("domain",appId+".vod2.myqcloud.com");
        urlAccessInfo.put("scheme","HTTP");
        try {
            Algorithm algorithm = Algorithm.HMAC256(playKey);
            psign = JWT.create().withClaim("appId", Integer.valueOf(appId)).withClaim("fileId", video.getVideoSourceId())
                    .withClaim("contentInfo", contentInfo)
                    .withClaim("currentTimeStamp", System.currentTimeMillis()/1000)//.withClaim("expireTimeStamp", PsignExpire)
                    .withClaim("urlAccessInfo", urlAccessInfo)
                    .sign(algorithm);
            System.out.println("token: "+psign);
        } catch (JWTCreationException exception) {
            // Invalid Signing configuration / Couldn't convert Claims.
            throw new CustomException(50000,"获取播放签名失败");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("psign",psign);
        map.put(VIDEO_SOURCE_ID,video.getVideoSourceId());
        map.put(APP_ID,appId);
        return map;
    }
}
